package com.gulimall.sso.client.controller;

import cn.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author lhj
 * @Date 2024/3/11 18:47
 */
@Controller
@RequestMapping("/sso/client")
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;

    @Value("${sso.client.url}")
    String ssoClientUrl;



    /**
     * 访问不需要保护的资源
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/employees")
    public String getEmployees(Model model, @RequestParam(value = "token", required = false) String token , HttpSession session) {
        if (!StringUtils.isEmpty(token)) {
            //根据token 查询用户信息然后放入到session中
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity("http://ssoserver.com:8080/sso/server/getUserInfo?token=" + token, String.class);
            session.setAttribute("loginUser", response.getBody());
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //重定向到认证服务器的登录页面
            return "redirect:" + ssoServerUrl + "?redirect_url=" + ssoClientUrl;
        }
        List<String> employees = new ArrayList<>();
        employees.add("张三");
        employees.add("李四");
        model.addAttribute("employees", employees);
        return "employees";
    }

}
